package com.xsmart.order.services.wx;

import com.baomidou.mybatisplus.plugins.Page;
import com.xsmart.common.constant.ResultConstant;
import com.xsmart.common.entity.RequestBean;
import com.xsmart.common.entity.ResponseBean;
import com.xsmart.order.dao.CartDao;
import com.xsmart.order.dao.GoodsManageDao;
import com.xsmart.order.dao.wx.WxOrderListDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * @author xuqinyuan
 */
@Service
public class WxOrderListService {

    @Autowired
    WxOrderListDao wxOrderListDao;

    @Autowired
    GoodsManageDao goodsManageDao;

    /**
     * 查询订单详情
     * @param requestBean
     * @return
     */
    public ResponseBean queryOrderDetail(RequestBean requestBean){
        Date now = new Date();
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Integer orderId = requestBean.getRequestParamInteger("orderId");
        Map<String, Object> orderMap = new HashMap<>();
        orderMap.put("orderId", orderId);
        ResponseBean responseBean = requestBean.getResponseBean();
        Map<String, Object> orderDetail = wxOrderListDao.quryOrderDetail(orderMap);
        List<Map<String, Object>> orderGoodsList = wxOrderListDao.queryOrderGoodsList(orderId);
        orderDetail.put("orderGoodsList",orderGoodsList);
        responseBean.addResultItem("orderDetail", orderDetail);
        responseBean.setResult(ResultConstant.SUCCESS);
        return responseBean;
    }

    /**
     * 查询订单
     * @param requestBean
     * @return
     */
    public ResponseBean queryOrderList(RequestBean requestBean){
        Date now=new Date();
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Integer userId = requestBean.getRequestParamInteger("userId");
        Integer orderStatus = requestBean.getRequestParamInteger("orderStatus");
        Integer shippingStatus = requestBean.getRequestParamInteger("shippingStatus");
        Integer payStatus = requestBean.getRequestParamInteger("payStatus");
        Map<String, Object> orderMap = new HashMap<>();
        orderMap.put("userId",userId);
        orderMap.put("orderStatus",orderStatus);
        orderMap.put("shippingStatus",shippingStatus);
        orderMap.put("payStatus",payStatus);
        ResponseBean responseBean = requestBean.getResponseBean();
        List<Map<String, Object>> orderList = wxOrderListDao.queryOrderList(orderMap);
        for(int i = 0;i<orderList.size();i++){
             Integer orderId = (Integer) orderList.get(i).get("order_id");
            List<Map<String, Object>> orderGoodsList = wxOrderListDao.queryOrderGoodsList(orderId);
            orderList.get(i).put("orderGoods",orderGoodsList);
        }
        responseBean.addResultItem("orderList", orderList);
        responseBean.setResult(ResultConstant.SUCCESS);
        return responseBean;
    }

    /**
     * 修改订单的订单状态
     * @param requestBean
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public ResponseBean modOrderStatus(RequestBean requestBean){
        Float costPrice = 0f;
        ResponseBean responseBean = requestBean.getResponseBean();
        Integer orderId = requestBean.getRequestParamInteger("id");
        String type = requestBean.getRequestParamString("type");
        Float orderAmount = requestBean.getRequestParamFloat("orderAmount");
        try {
            Map<String,Object> orderStatus = wxOrderListDao.getOrderStatus(orderId);
            orderStatus.put("order_id",orderId);
            if("cancel".equals(type)) {
                List<Map<String, Object>> goodsList = wxOrderListDao.queryOrderGoodsNumber(orderId);
                if(!orderStatus.get("pay_status").equals(2)) {
                    orderStatus.put("order_status", 2);
                    int num = wxOrderListDao.modOrderStatus(orderStatus);
                    for (int i = 0; i < goodsList.size(); i++){
                        int num3 = goodsManageDao.updateGoodsNum(goodsList.get(i));
                    }
                    responseBean.setResult(ResultConstant.SUCCESS);
                }else{
                    responseBean.setResult(ResultConstant.ERROR);
                }
            }else if("receive".equals(type)){
                orderStatus.put("shipping_status", 2);
                int num1 = wxOrderListDao.modOrderStatus(orderStatus);
                responseBean.setResult(ResultConstant.SUCCESS);
            }else if("delete".equals(type)){
                System.out.print( orderStatus);
                orderStatus.put("order_status", 5);
                int num2 = wxOrderListDao.modOrderStatus(orderStatus);
                responseBean.setResult(ResultConstant.SUCCESS);
            }else if("confirmPay".equals(type)){
                //确认支付
                if ("0".equals(orderStatus.get("order_status")) && "0".equals(orderStatus.get("shipping_status"))
                        && "2".equals(orderStatus.get("pay_status"))){
                    responseBean.setMessage("已经支付完成");
                }else {
                    Date day=new Date();
                    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    orderStatus.put("order_status", 0);
                    orderStatus.put("shipping_status", 0);
                    orderStatus.put("pay_status", 2);
                    orderStatus.put("pay_time", df.format(day));
                    int num3 = wxOrderListDao.modOrderStatus(orderStatus);
                }

                List<Map<String, Object>> orderGoodsList = wxOrderListDao.queryOrderGoodsList(orderId);
                for (int i = 0; i < orderGoodsList.size(); i++){
                    costPrice += Float.parseFloat(orderGoodsList.get(i).get("cost_price").toString())
                            * Integer.parseInt(orderGoodsList.get(i).get("goods_number").toString());
                }
                List<Map<String, Object>> queryOrderSettleList = wxOrderListDao.queryOrderSettle(orderId);
                if (queryOrderSettleList.size() == 0){
                    Map<String, Object> orderSettleMap = new HashMap<>();
                    orderSettleMap.put("order_id", orderId);
                    orderSettleMap.put("cost_price", costPrice);
                    orderSettleMap.put("goods_amount", orderAmount);
                    orderSettleMap.put("order_profit", orderAmount - costPrice);
                    int num4 = wxOrderListDao.addOrderSettle(orderSettleMap);
                }
                responseBean.setResult(ResultConstant.SUCCESS);
            }else {
                responseBean.setResult(ResultConstant.ERROR);
            }
        }catch (Exception e){
            e.printStackTrace();
            responseBean.setResult(ResultConstant.ERROR);
        }
        return  responseBean;
    }

    /**
     * 查询订单数量
     * @param requestBean
     * @return
     */
    public ResponseBean queryOrderCount(RequestBean requestBean){
        Integer userId = requestBean.getRequestParamInteger("userId");
        List<String> status =  (List<String>)requestBean.getRequestParam("status");
        int nopayCount = 0;
        int paidCount = 0;
        int finishedCount = 0;
        int deliveryCount = 0;
        int refundCount = 0;
        for (int i = 0;i<status.size();i++){
            if (status.get(i).equals("nopay")){
                //待付款
                nopayCount = wxOrderListDao.queryOrderCountByStatus(userId,0,0,0);
            }else if (status.get(i).equals("delivery")){
                //待发货
                deliveryCount = wxOrderListDao.queryOrderCountByStatus(userId,0,0,2);
            }else if (status.get(i).equals("paid")){
                //待收获
                paidCount = wxOrderListDao.queryOrderCountByStatus(userId,0,1,2);
            }else if (status.get(i).equals("finished")){
                //已完成
                finishedCount = wxOrderListDao.queryOrderCountByStatus(userId,1,2,2);
            }else if (status.get(i).equals("refund")){
                //退款售后
                refundCount = wxOrderListDao.queryOrderCountByStatus(userId,4,4,2);
            }
        }
        ResponseBean responseBean = requestBean.getResponseBean();
        responseBean.addResultItem("nopayCount", nopayCount);
        responseBean.addResultItem("paidCount", paidCount);
        responseBean.addResultItem("finishedCount", finishedCount);
        responseBean.addResultItem("deliveryCount", deliveryCount);
        responseBean.addResultItem("refundCount", refundCount);
        responseBean.setResult(ResultConstant.SUCCESS);
        return responseBean;
    }

    /**
     * 查询分销商的订单
     * @param requestBean
     * @return
     */
    public ResponseBean queryDistributerOrder(RequestBean requestBean){
        Integer userId = requestBean.getRequestParamInteger("userId");
        Integer orderStatus = requestBean.getRequestParamInteger("orderStatus");
        Integer shippingStatus = requestBean.getRequestParamInteger("shippingStatus");
        Integer payStatus = requestBean.getRequestParamInteger("payStatus");
        Map<String, Object> orderMap = new HashMap<>();
        orderMap.put("userId",userId);
        orderMap.put("orderStatus",orderStatus);
        orderMap.put("shippingStatus",shippingStatus);
        orderMap.put("payStatus",payStatus);
        ResponseBean responseBean = requestBean.getResponseBean();
        List<Map<String, Object>> orderList = wxOrderListDao.queryDistributerOrder(orderMap);
        for(int i = 0;i<orderList.size();i++){
            Integer orderId = (Integer) orderList.get(i).get("order_id");
            List<Map<String, Object>> orderGoodsList = wxOrderListDao.queryOrderGoodsList(orderId);
            orderList.get(i).put("orderGoods",orderGoodsList);
        }
        responseBean.addResultItem("orderList", orderList);
        responseBean.setResult(ResultConstant.SUCCESS);
        return responseBean;
    }


    /**
     * 查询分销商的订单数量
     * @param requestBean
     * @return
     */
    public ResponseBean queryDistributerOrderCount(RequestBean requestBean){
        Integer userId = requestBean.getRequestParamInteger("userId");
        int distributerOrderCount = wxOrderListDao.queryDistributerOrderCount(userId);
        ResponseBean responseBean = requestBean.getResponseBean();
        responseBean.addResultItem("distributerOrderCount",distributerOrderCount);
        responseBean.setResult(ResultConstant.SUCCESS);
        return responseBean;
    }

    /**
     * 查询分销商的下线会员信息
     * @param requestBean
     * @return
     */
    public ResponseBean queryDistributorMember(RequestBean requestBean){
        Integer userId = requestBean.getRequestParamInteger("userId");
        List<Map<String,Object>> memberList = wxOrderListDao.queryDistributorMember(userId);
        ResponseBean responseBean = requestBean.getResponseBean();
        responseBean.addResultItem("memberList",memberList);
        responseBean.setResult(ResultConstant.SUCCESS);
        return responseBean;
    }

    /**
     * 新增订单结算记录
     * @param requestBean
     * @return
     */
    public ResponseBean addOrderSettle(RequestBean requestBean){
        Integer orderId = requestBean.getRequestParamInteger("order_id");
        Float costPrice = requestBean.getRequestParamFloat("cost_price");
        Float goodsAmount = requestBean.getRequestParamFloat("goods_amount");
        Float orderProfit = requestBean.getRequestParamFloat("order_profit");
        Map<String, Object> orderSettleMap = new HashMap<>();
        orderSettleMap.put("order_id", orderId);
        orderSettleMap.put("cost_price", costPrice);
        orderSettleMap.put("goods_amount", goodsAmount);
        orderSettleMap.put("order_profit", orderProfit);
        int num = wxOrderListDao.addOrderSettle(orderSettleMap);
        ResponseBean responseBean = requestBean.getResponseBean();
        return responseBean;
    }


}
